import java.text.SimpleDateFormat
import java.text.DecimalFormat

def execute(data, dlzt) {
    //主表
    def PO_Pomain = data["PO_Pomain"];
    def cVenCode = PO_Pomain[0]["cVenCode"];//供应商名称
    def cDepCode = PO_Pomain[0]["cDepCode"];//部门名称
    def cPersonCode = PO_Pomain[0]["cPersonCode"];//人员名称
    def cPTCode = PO_Pomain[0]["cPTCode"];//采购类型名称
    def iTaxRate = PO_Pomain[0]["iTaxRate"];//税率
    def cMaker = PO_Pomain[0]["cMaker"];//制单人
    def cMemo = PO_Pomain[0]["cMemo"];//备注
    def cVerifier = PO_Pomain[0]["cVerifier"];//审核人
    //子表
    def PO_Podetails = data["PO_Podetails"];
    //采购订单新增
    def conn = null;
    def list = [];
    def result = [];
    try {
        conn = groovy.sql.Sql.newInstance("jdbc:sqlserver://192.168.1.2;databaseName=UFDATA_001_2022", "sa", "ABC.123", "com.microsoft.sqlserver.jdbc.SQLServerDriver");
        //        conn = groovy.sql.Sql.newInstance(dlzt.hqcon(3))
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        SimpleDateFormat sdf2 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.sss");
        //获取供应商信息
        def cVenCode2 = conn.firstRow("select cVenCode from Vendor where cVenCode='" + cVenCode + "'");
        if (cVenCode2 == null) {
            return ["state": "0", "Ascript": "供应商编码'" + cVenCode + "'不存在，并且不能为空，请重新输入！", "result": []];
        }
        //获取部门信息
        def cDepCode2 = conn.firstRow("select cDepCode from Department where cDepCode='" + cDepCode + "'");
        if (cDepCode2 == null) {
            return ["state": "0", "Ascript": "部门编码'" + cDepCode + "'不存在，并且不能为空，请重新输入！", "result": []];
        }
        //获取业务员信息
        def cPersonCode2 = conn.firstRow("select cPersonCode from Person a left join Department b on a.cDepCode=b.cDepCode where cPersonCode='" + cPersonCode + "' and b.cDepCode='" + cDepCode + "'");
        if (cPersonCode2 == null) {
            return ["state": "0", "Ascript": "部门'" + cDepCode + "'下没有这条业务员编码'" + cPersonCode + "'信息，并且不能为空，请重新输入！", "result": []];
        }
        //采购类型信息
        def cPTCode2 = conn.firstRow("select cPTCode from PurchaseType where cPTCode='" + cPTCode + "'");
        if (cPTCode2 == null) {
            return ["state": "0", "Ascript": "采购类型编码'" + cPTCode + "'不存在，并且不能为空，请重新输入！", "result": []];
        }
        if (iTaxRate == null || iTaxRate.equals("")) {
            return ["state": "0", "Ascript": "税率不能为空，请重新输入！", "result": []];
        }
        //遍历子表集合插入验证
        for (int i = 0; i < PO_Podetails.size(); i++) {
            def cInvCode = PO_Podetails.get(i).cInvCode; //存货编码
            def iQuantity = PO_Podetails.get(i).iQuantity;//数量
            def iUnitPrice = PO_Podetails.get(i).iUnitPrice;//原币无税单价
            def iMoney = PO_Podetails.get(i).iMoney;//原币无税金额
            def iTax = PO_Podetails.get(i).iTax;//原币税额
            def iSum = PO_Podetails.get(i).iSum;//原币价税合计
            def iTaxPrice = PO_Podetails.get(i).iTaxPrice;//原币含税单价
            def dArriveDate = PO_Podetails.get(i).dArriveDate;//计划到货日期
            //存货判断
            if (cInvCode == null || cInvCode.equals("")) {
                return ["state": "0", "Ascript": "在第" + (i + 1) + "行,输入的存货编码不能为空,请重新输入", "result": []];
            }
            //判断传入的存货在数据库中是否存在
            def dd = conn.firstRow("select cInvCode from Inventory where cInvCode='" + cInvCode + "'")
            if (dd == null) {
                return ["state": "0", "Ascript": "在第" + (i + 1) + "行,存货编码'" + cInvCode + "'不存在，并且不能为空，请重新输入！", "result": []];
            }
            //数量判断
            if (iQuantity == null || iQuantity.equals("")) {
                return ["state": "0", "Ascript": "在第" + (i + 1) + "行,输入的数量不能为空,请重新输入", "result": []];
            }
            //原币无税单价判断
            if (iUnitPrice == null || iUnitPrice.equals("")) {
                return ["state": "0", "Ascript": "在第" + (i + 1) + "行,输入的原币无税单价不能为空,请重新输入", "result": []];
            }
            //原币无税金额判断
            if (iMoney == null || iMoney.equals("")) {
                return ["state": "0", "Ascript": "在第" + (i + 1) + "行,输入的原币无税金额不能为空,请重新输入", "result": []];
            }
            //原币税额判断
            if (iTax == null || iTax.equals("")) {
                return ["state": "0", "Ascript": "在第" + (i + 1) + "行,输入的原币税额不能为空,请重新输入", "result": []];
            }
            //原币价税合计判断
            if (iSum == null || iSum.equals("")) {
                return ["state": "0", "Ascript": "在第" + (i + 1) + "行,输入的原币价税合计不能为空,请重新输入", "result": []];
            }
            //原币含税单价判断
            if (iTaxPrice == null || iTaxPrice.equals("")) {
                return ["state": "0", "Ascript": "在第" + (i + 1) + "行,输入的原币含税单价不能为空,请重新输入", "result": []];
            }
            //计划到货日期判断
            if (dArriveDate == null || dArriveDate.equals("")) {
                return ["state": "0", "Ascript": "在第" + (i + 1) + "行,输入的计划到货日期不能为空,请重新输入", "result": []];
            }
            //金额转换
            BigDecimal busoppnums = new BigDecimal(iSum.toString());
            def sum = busoppnums.setScale(4, BigDecimal.ROUND_HALF_UP);
            BigDecimal num1 = new BigDecimal(iMoney.toString());//把金额转换成BigDecimal
            def num3 = num1.setScale(4, BigDecimal.ROUND_HALF_UP); //转换num1
            BigDecimal num2 = new BigDecimal(iTax.toString());//把税额转换成BigDecimal
            def num4 = num2.setScale(4, BigDecimal.ROUND_HALF_UP);//转换num2
            def cc = num3 + num4
            if (!cc.equals(sum)) {
                return ["state": "0", "Ascript": "在第" + (i + 1) + "行,原币金额+税额不等于原币价税合计,请重新输入", "result": []];
            }
            if (iMoney.toString().split("\\.").length > 1) {
                if (iMoney.toString().split("\\.")[0].length() != 2) {
                    return ["state": "0", "Ascript": "在第" + (i + 1) + "行,输入的原币无税金额保留二位有效数字,请重新输入", "result": []];
                }
            } else if (iTax.toString().split("\\.").length > 1) {
                if (iTax.toString().split("\\.")[0].length() != 2) {
                    return ["state": "0", "Ascript": "在第" + (i + 1) + "行,输入的原币税额保留二位有效数字,请重新输入", "result": []];
                }
            } else if (iSum.toString().split("\\.").length > 1) {
                if (iSum.toString().split("\\.")[0].length() != 2) {
                    return ["state": "0", "Ascript": "在第" + (i + 1) + "行,输入的原币价税合计保留二位有效数字,请重新输入", "result": []];
                }
            } else if (iUnitPrice.toString().split("\\.").length > 1) {
                if (iUnitPrice.toString().split("\\.")[0].length() != 2) {
                    return ["state": "0", "Ascript": "在第" + (i + 1) + "行,输入的原币无税单价保留二位有效数字,请重新输入", "result": []];
                }
            } else if (iTaxPrice.toString().split("\\.").length > 1) {
                if (iTaxPrice.toString().split("\\.")[0].length() != 2) {
                    return ["state": "0", "Ascript": "在第" + (i + 1) + "行,输入的原币含税单价保留二位有效数字,请重新输入", "result": []];
                }
            }
            //判断有没有输入dArriveDate
            if (dArriveDate == null || dArriveDate.equals("")) {
                return ["state": "0", "Ascript": "在第" + (i + 1) + "行,请输入计划到货日期", "result": []];
            }
            def dPODate = sdf.format(new Date())
            //判断dArriveDate是否大于dPODate
            if (dArriveDate < dPODate) {
                return ["state": "0", "Ascript": "在第" + (i + 1) + "行,计划到货日期必须大于等于制单日期", "result": []];
            }
        }
        //查询单据编号生成控制表中的iFatherId iChildId
        def maxID = conn.firstRow("select iFatherId,iChildId from UFSystem..UA_Identity where cVouchType='Pomain' and cAcc_Id='001'");
        //如果单据编号生成控制表中不存在 直接添加 存在就修改
        def iFatherId
        def iChildId
        if (maxID == null) {
            iFatherId = 1;
            iChildId = 1;
        } else {
            iFatherId = maxID.iFatherId + 1;
            iChildId = maxID.iChildId + 1;
        }
        //查询最大采购订单号
        def cPOID = conn.rows("select REPLICATE('0',10-len(max(cPOID)+1))+cast(max(cPOID)+1 AS varchar(10)) as cc from PO_Pomain")[0][0];
        if (cPOID == null) {
            cPOID = "0000000001"
        }
        //获取最大采购订单主表标识
        def POID = conn.rows("select REPLICATE('0',10-len(max(POID)+1))+cast(max(POID)+1 AS varchar(10)) as cc from PO_Pomain")[0][0];
        if (POID == null) {
            POID = "1000000001"
        }
        //获取单据日期
        def dPODate = sdf.format(new Date());
        //获取制单时间 
        def cmaketime = sdf2.format(new Date());
        //获取审核日期
        def cAuditDate = sdf.format(new Date());
        //获取审核时间
        def cAuditTime = sdf2.format(new Date());
        conn.withTransaction {
            //表体循环新增
            for (def s = 0; s < PO_Podetails.size(); s++) {
                //获取最大ID 子表标识
                def ID = conn.rows("select REPLICATE('0',10-len(max( )+1))+cast(max(ID)+1 AS varchar(10)) as cc from PO_Podetails")[0][0];
                if (ID == null) {
                    ID = "1000000001";
                }
                def ivouchrowno = s + 1;//行号
                //单据条码拼接
                def csysbarcode = "||pupo|" + cPOID;
                //获取cbsysbarcode行条码
                def cbsysbarcode = csysbarcode + "|" + ivouchrowno;
                if (s == 0) {
                    //新增表头信息
                    def inserttou = "insert into PO_Pomain(cPOID,dPODate,cVenCode,cDepCode,cPersonCode,cPTCode,cexch_name,nflat,iTaxRate,cMemo,cState,cMaker,POID,cBusType,cmaketime,csysbarcode,iVTid,cVerifier,cAuditDate,cAuditTime,cDefine13) values('" + cPOID + "','" + dPODate + "','" + cVenCode2.cVenCode + "','" + cDepCode2.cDepCode + "','" + cPersonCode2.cPersonCode + "','" + cPTCode2.cPTCode + "','人民币',1,'" + iTaxRate + "','" + cMemo + "',1,'" + cMaker + "','" + POID + "','普通采购','" + cmaketime + "','" + csysbarcode + "',8173,'" + cVerifier + "','" + cAuditDate + "','" + cAuditTime + "','srm导入')"
                    conn.execute(inserttou)
                    //新增表体信息
                    def insertti = "insert into PO_Podetails(ID,cInvCode,iQuantity,iUnitPrice,iMoney,iTax,iSum,iNatUnitPrice,iNatMoney,iNatTax,iNatSum,dArriveDate,iPerTaxRate,POID,iTaxPrice,ivouchrowno,cbsysbarcode) values('" + ID + "','" + PO_Podetails.get(s).cInvCode + "'," + PO_Podetails.get(s).iQuantity + "," + PO_Podetails.get(s).iUnitPrice + "," + PO_Podetails.get(s).iMoney + "," + PO_Podetails.get(s).iTax + "," + PO_Podetails.get(s).iSum + "," + PO_Podetails.get(s).iUnitPrice + "," + PO_Podetails.get(s).iMoney + "," + PO_Podetails.get(s).iTax + "," + PO_Podetails.get(s).iSum + ",'" + PO_Podetails.get(s).dArriveDate + "'," + PO_Podetails.get(s).iTaxRate + ",'" + POID + "'," + PO_Podetails.get(s).iTaxPrice + ",'" + ivouchrowno + "','" + cbsysbarcode + "')"
                    conn.execute(insertti)
                    //修改单据编号生成控制表
                    if (maxID == null) {
                        conn.execute("insert into UFSystem..UA_Identity(cAcc_Id,cVouchType,iFatherId,iChildId) values('001','Pomain'," + iFatherId + "," + iChildId + ")")
                    } else {
                        conn.execute("update UFSystem..UA_Identity set iFatherId=" + iFatherId + ",iChildId=" + iChildId + " where cVouchType='Pomain' and cAcc_Id='001'")
                    }
                } else {
                    iChildId = iChildId + 1
                    //新增表体信息
                    def insertti = "insert into PO_Podetails(ID,cInvCode,iQuantity,iUnitPrice,iMoney,iTax,iSum,iNatUnitPrice,iNatMoney,iNatTax,iNatSum,dArriveDate,iPerTaxRate,POID,iTaxPrice,ivouchrowno,cbsysbarcode) values('" + ID + "','" + PO_Podetails.get(s).cInvCode + "'," + PO_Podetails.get(s).iQuantity + "," + PO_Podetails.get(s).iUnitPrice + "," + PO_Podetails.get(s).iMoney + "," + PO_Podetails.get(s).iTax + "," + PO_Podetails.get(s).iSum + "," + PO_Podetails.get(s).iUnitPrice + "," + PO_Podetails.get(s).iMoney + "," + PO_Podetails.get(s).iTax + "," + PO_Podetails.get(s).iSum + ",'" + PO_Podetails.get(s).dArriveDate + "'," + PO_Podetails.get(s).iTaxRate + ",'" + POID + "'," + PO_Podetails.get(s).iTaxPrice + ",'" + ivouchrowno + "','" + cbsysbarcode + "')"
                    conn.execute(insertti)
                    //修改单据编号生成控制表
                    conn.execute("update UFSystem..UA_Identity set iChildId=" + iChildId + " where cVouchType='Pomain' and cAcc_Id='001'")
                }
            }
        }
        list = conn.rows("SELECT a.cPOID,b.cInvCode,b.Id,c.cInvName FROM PO_Pomain a LEFT JOIN PO_Podetails b ON a.POID= b.POID LEFT JOIN Inventory c ON b.cInvCode= c.cInvCode WHERE a.cPOID= '" + cPOID + "'")
    } catch (Exception e) {
        e.printStackTrace()
        return ["state": "0", "Ascript": "脚本执行错误", "result": []]
    } finally {
        if (conn != null) {
            conn.close()
        }
    }
    //返回数据物料和子件主键id
    for (def t : list) {
        result << ["cPOID": t["cPOID"], "ID": t["ID"], "cInvCode": t["cInvCode"], "cInvName": t["cInvName"]]
    }
    return ["state": "1", "Ascript": "新增成功", "result": result]
}